package org.duomn.ichat.net.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;

import org.duomn.ichat.entity.FileMessage;
import org.duomn.ichat.entity.Message;
import org.duomn.ichat.entity.MsgType;
import org.duomn.ichat.exception.MsgHandleException;
import org.duomn.ichat.net.AbstractMsgHandler;
import org.duomn.ichat.thread.TCPThreadAbstract;
import org.duomn.ichat.util.IOUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class FileMsgHandler extends AbstractMsgHandler {
	
	private static Logger logger = LoggerFactory.getLogger(FileMsgHandler.class);

	public FileMsgHandler(TCPThreadAbstract chatThread, Message message) {
		super(chatThread, message);
	}

	@Override
	public void handle() throws ClassNotFoundException,
			SocketException, IOException {
		FileMessage message = (FileMessage) chatThread.getInputStream().readObject();
		try {
			handMsg(message);
		} catch (MsgHandleException e) {
			throw new IOException(e);
		}
	}

	@Override
	protected void handMsg(Message msg) throws MsgHandleException {
		FileMessage message = (FileMessage) msg;
		if (message.fileMsgType == FileMsgType.FILE_INFO) {
			// TODO 收到文件信息，在列表中展示
		} else if (message.fileMsgType == FileMsgType.FILE_ACCESS_REV) {
			// TODO 收到同意消息后，发送文件列表中的文件
			
		} else if (message.fileMsgType == FileMsgType.FILE_REFUSE_REV) {
			// TODO 主动线程收到拒绝消息后，移除文件列表中传输的文件 
			
		}
		if (message.fileMsgType == FileMsgType.FILE_TRAN_HEAD) {
			logger.debug("recevie file, storage path-[" + message.storageFile + "], size:" + message.fileSize + ".");
			File file = new File(message.storageFile);
			
			FileOutputStream out = null; 
			try {
				out = new FileOutputStream(file);
				IOUtil.copyStream(chatThread.getInputStream(), out, message.fileSize);
			} catch (FileNotFoundException e) {
				logger.error("Save the file to path '" + message.storageFile + "', was not found file", e);
				throw new MsgHandleException(e);
			} catch (IOException e) {
				logger.error("Handle File Msg with Exception", e);
				throw new MsgHandleException(e);
			} finally {
				if (out != null) {
					try {
						out.close();
					} catch (IOException e) {
						logger.error("Close the file out stream happend exception", e);
						throw new MsgHandleException(e);
					}
				}
			}
		} else if (msg.msgType == MsgType.CLOSE_SESSION) {
			chatThread.closeByReceive();
		}
	}

	


}
